package com.atguigu.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.search.config.GulimallElasticSearchConfig;
import com.atguigu.gulimall.search.constant.EsConstant;
import com.atguigu.gulimall.search.feign.ProductFeignService;
import com.atguigu.gulimall.search.service.MallSearchService;
import com.atguigu.gulimall.search.vo.AttrResponseVo;
import com.atguigu.gulimall.search.vo.BrandVo;
import com.atguigu.gulimall.search.vo.SearchParam;
import com.atguigu.gulimall.search.vo.SearchResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.stream.Collectors;

@Slf4j
@Service
public class MallSearchServiceImpl implements MallSearchService {

    @Qualifier("esRestClient")
    @Autowired
    private RestHighLevelClient highLevelClient;

    @Autowired
    private ProductFeignService productFeignService;

    @Override
    public SearchResult search(SearchParam param) {
        SearchResult searchResult = null;
        // 准备检索请求
        SearchRequest searchRequest = buildSearchRequest(param);

        try {
            // 执行查询
            SearchResponse searchResponse = highLevelClient.search(searchRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);

            // 分析相应数据，封装数据
            searchResult = buildSearchResult(param, searchResponse);
        } catch (IOException exception) {
            exception.printStackTrace();
        }

        return searchResult;
    }

    /**
     * 准备检索请求
     * @return
     */
    private SearchRequest buildSearchRequest(SearchParam param) {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        /*
         * 1 模糊匹配  属性、分类、品牌、价格区间、库存
         */
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery(); // bool query
        // 1.1 bool - must
        if (!StringUtils.isEmpty(param.getKeyword())) {
            boolQuery.must(QueryBuilders.matchQuery("skuTitle", param.getKeyword()));
        }
        // 1.2 bool - filter
        if (param.getCatalog3Id() != null) { //分类
            boolQuery.filter(QueryBuilders.termQuery("catalogId", param.getCatalog3Id()));
        }
        if (param.getBrandId() != null && param.getBrandId().size() > 0) { //品牌列表
            boolQuery.filter(QueryBuilders.termsQuery("brandId", param.getBrandId()));
        }
        // 属性
        if (param.getAttrs() != null && param.getAttrs().size() > 0) {
            // 请求Example  attrs=1_5寸&attrs=2_16G:8G
            for (String attrStr : param.getAttrs()) {
                // 创建 NestedQuery 请求体
                BoolQueryBuilder nestedBoolQuery = QueryBuilders.boolQuery();

                String[] split = attrStr.split("_");
                // 属性的id
                String attrId = split[0];
                // 属性允许的值
                String[] attrValues = split[1].split(":");

                // 封装nested查询
                nestedBoolQuery.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                nestedBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));
                // 将 BoolQuery 放入 NestedQuery，每一个都得生成一个嵌入式的 NestedQuery
                NestedQueryBuilder nested = QueryBuilders.nestedQuery("attrs", nestedBoolQuery, ScoreMode.None);
                // 加入外层的 boolQuery
                boolQuery.filter(nested);
            }
        }

        if (param.getHasStock() != null) { //是否有库存
            boolQuery.filter(QueryBuilders.termQuery("hasStock", param.getHasStock() != 0));
        }
        if (!StringUtils.isEmpty(param.getSkuPrice())) { //价格区间
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");

            String[] split = param.getSkuPrice().split("_");
            if (split.length == 2) {
                // 1_500 或 _500
                if ("".equals(split[0])) {
                    // _500
                    rangeQuery.lte(split[1]);
                } else {
                    // 1_500
                    rangeQuery.gte(split[0]);
                    rangeQuery.lte(split[1]);
                }
            } else if (split.length == 1) {
                // 500_ 或 500
                if (param.getSkuPrice().endsWith("_")) {
                    // 500_
                    rangeQuery.gte(split[0]);
                }
            }
            boolQuery.filter(rangeQuery);
        }

        // --- 将大的 boolQuery 放入请求体 ---
        sourceBuilder.query(boolQuery);

        /*
         * 排序 高亮
         */
        // 排序
        if (!StringUtils.isEmpty(param.getSort())) {
            String sort = param.getSort();
            String[] split = sort.split("_");
            // 加入排序
            SortOrder sortOrder = "asc".equalsIgnoreCase(split[1]) ? SortOrder.ASC : SortOrder.DESC;
            sourceBuilder.sort(split[0], sortOrder);
        }
        // 分页
        if (param.getPageNum() == null)
            param.setPageNum(1);
        sourceBuilder.from((param.getPageNum() - 1) * EsConstant.PRODUCT_PAGE_SIZE);
        sourceBuilder.size(EsConstant.PRODUCT_PAGE_SIZE);
        // 高亮
        if (!StringUtils.isEmpty(param.getKeyword())) {
            // 构造HighlightBuilder
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            // 放入查询条件
            sourceBuilder.highlighter(highlightBuilder);
        }

        /*
         * 聚合分析
         */
        // 品牌聚合
        TermsAggregationBuilder brandAgg = AggregationBuilders.terms("brand_agg");
        brandAgg.field("brandId").size(50);
        // 品牌聚合的子聚合
        brandAgg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brandAgg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        // 放入 sourceBuilder
        sourceBuilder.aggregation(brandAgg);

        // 分类聚合
        TermsAggregationBuilder catalogAgg = AggregationBuilders.terms("catalog_agg").field("catalogId").size(20);
        catalogAgg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        // 放入 sourceBuilder
        sourceBuilder.aggregation(catalogAgg);

        // 属性聚合
        NestedAggregationBuilder attrAgg = AggregationBuilders.nested("attr_agg", "attrs");
        // 子聚合attrIdAgg
        TermsAggregationBuilder attrIdAgg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");
        attrIdAgg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        attrIdAgg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50));

        attrAgg.subAggregation(attrIdAgg);
        sourceBuilder.aggregation(attrAgg);


        // 执行查询
        String dsl = sourceBuilder.toString();
        System.out.println("构建的DSL查询语句：" + dsl);

        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, sourceBuilder);
        return searchRequest;
    }

    /**
     * 构建结果数据
     * @param searchResponse
     * @return
     */
    private SearchResult buildSearchResult(SearchParam param, SearchResponse searchResponse) {
        SearchResult result = new SearchResult();

        // 1.返回所有查询到的商品
        SearchHits hits = searchResponse.getHits();
        List<SkuEsModel> esModels = new ArrayList<>(hits.getHits().length);
        if (hits.getHits() != null && hits.getHits().length > 0) {
            for (SearchHit hit : hits.getHits()) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel esModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
                // 搜索关键字不为空，则标题有高亮
                if (!StringUtils.isEmpty(param.getKeyword())) {
                    HighlightField highlight = hit.getHighlightFields().get("skuTitle");
                    String highlightSkuTitleStr = highlight.getFragments()[0].string();
                    esModel.setSkuTitle(highlightSkuTitleStr);
                }
                esModels.add(esModel);
            }
        }
        result.setProducts(esModels);
        // 2.当前所有商品涉及到的所有属性信息
        ParsedNested attrAgg = searchResponse.getAggregations().get("attr_agg");
        List<SearchResult.AttrVo> attrVos = new ArrayList<>();
        ParsedLongTerms attrIdAgg = attrAgg.getAggregations().get("attr_id_agg");
        for (Terms.Bucket bucket : attrIdAgg.getBuckets()) {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            // 遍历每一个属性  取出id
            long attrId = bucket.getKeyAsNumber().longValue();
            attrVo.setAttrId(attrId);
            // 取得name
            String attrName = ((ParsedStringTerms) bucket.getAggregations().get("attr_name_agg")).getBuckets().get(0).getKeyAsString();
            attrVo.setAttrName(attrName);
            // 遍历子聚合 获取每一个value
            List<String> attrValueList = ((ParsedStringTerms) bucket.getAggregations().get("attr_value_agg")).getBuckets().stream().map(b -> {
                String attrValue = b.getKeyAsString();
                return attrValue;
            }).collect(Collectors.toList());
            attrVo.setAttrValue(attrValueList);
            // 放入list
            attrVos.add(attrVo);
        }
        result.setAttrs(attrVos);

        // 3.当前所有商品涉及到的所有品牌信息
        ParsedLongTerms brandAgg = searchResponse.getAggregations().get("brand_agg");
        List<SearchResult.BrandVo> brandVos = new ArrayList<>();
        for (Terms.Bucket bucket : brandAgg.getBuckets()) {
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            // 3.1 品牌的Id
            long brandId = bucket.getKeyAsNumber().longValue();
            brandVo.setBrandId(brandId);
            // 3.2 品牌的名字
            String brandName = ((ParsedStringTerms) bucket.getAggregations().get("brand_name_agg")).getBuckets().get(0).getKeyAsString();
            brandVo.setBrandName(brandName);
            // 3.3 品牌的图片
            String brandImg = ((ParsedStringTerms) bucket.getAggregations().get("brand_img_agg")).getBuckets().get(0).getKeyAsString();
            brandVo.setBrandImg(brandImg);
            // 加入list
            brandVos.add(brandVo);
        }
        result.setBrands(brandVos);

        // 4.当前所有商品涉及到的所有分类信息
        ParsedLongTerms catalogAgg = searchResponse.getAggregations().get("catalog_agg");
        List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
        for (Terms.Bucket bucket : catalogAgg.getBuckets()) {
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            //得到分类id
            long catalogId = Long.parseLong(bucket.getKeyAsString());
            catalogVo.setCatalogId(catalogId);
            // 得到分类的名字 子聚合
            ParsedStringTerms catalogNameAgg = bucket.getAggregations().get("catalog_name_agg");
            String catalogName = catalogNameAgg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(catalogName);
            // 放入列表
            catalogVos.add(catalogVo);
        }
        result.setCatalogs(catalogVos);

        // 5.分类信息-页码
        long total = hits.getTotalHits().value;
        result.setTotal(total);
        result.setTotalPages((int) (total % EsConstant.PRODUCT_PAGE_SIZE == 0 ? total / EsConstant.PRODUCT_PAGE_SIZE : total / EsConstant.PRODUCT_PAGE_SIZE + 1));
        result.setPageNum(param.getPageNum());

        List<Integer> pageNavs = new ArrayList<>(result.getTotalPages());
        for (int i = 0; i < result.getTotalPages(); i++) {
            pageNavs.add(i + 1);
        }
        result.setPageNavs(pageNavs);

        // 6.构建面包屑导航功能
        if (param.getAttrs() != null && param.getAttrs().size() > 0) {
            List<SearchResult.NavVo> collect = param.getAttrs().stream().map(attr -> {
                SearchResult.NavVo navVo = new SearchResult.NavVo();
                String[] s = attr.split("_");
                navVo.setNavValue(s[1]);
                // RPC查询服务名
                R r = productFeignService.attrInfo(Long.parseLong(s[0]));
                result.getAttrIds().add(Long.parseLong(s[0]));
                if (r.getCode() == 0) {
                    AttrResponseVo attrRespVo = (AttrResponseVo) r.getData("attr", new TypeReference<AttrResponseVo>(){});
                    navVo.setNavName(attrRespVo.getAttrName());
                } else {
                    navVo.setNavName(s[0]);
                    log.error("远程调用AttrInfo失败", "错误码是" + r.getCode());
                }

                // 取消了面包屑后要跳转的地方
                String closeUrl = replaceQueryString(param, attr, "attrs");
                navVo.setLink("http://search.gulimall.com/list.html?" + closeUrl);

                return navVo;
            }).collect(Collectors.toList());
            result.setNavs(collect);
        }

        // 品牌分类
        if (param.getBrandId() != null && param.getBrandId().size() > 0) {
            List<SearchResult.NavVo> navs = result.getNavs();
            SearchResult.NavVo navVo = new SearchResult.NavVo();
            navVo.setNavName("品牌");
            // RPC查询商品服务 品牌的中文名
            R r = productFeignService.brandsInfo(param.getBrandId());
            if (r.getCode() == 0) {
                List<BrandVo> brands = (List<BrandVo>) r.getData("brand", new TypeReference<List<BrandVo>>() {});
                StringBuilder builder = new StringBuilder();
                String replace = "";
                for (BrandVo brandVo : brands) {
                    builder.append(brandVo.getBrandName());
                    replace = replaceQueryString(param, brandVo.getBrandId() + "", "brandId");
                }
                navVo.setNavName(builder.toString());
                navVo.setLink("http://search.gulimall.com/list.html?" + replace);
            }
            navs.add(navVo);
        }

        // TODO 分类的面包屑标签


        return result;
    }

    private String replaceQueryString(SearchParam param, String attr, String key) {
        String encode = null;
        try {
            encode = URLEncoder.encode(attr, "UTF-8");
            encode = encode.replace("+", "%20");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return param.get_queryString().replace(key + "=" + encode, "");
    }


}
